<?php
/**
 * Created by PhpStorm.
 * User: 盛茂国
 * Tel: 18394333958
 * Date: 2020/6/2
 * Time: 10:31
 */
namespace app\api\controller;


use app\common\controller\Api;
use think\Request;

class Comment extends Api
{
    protected $noNeedLogin = ['add'];
    protected $noNeedRight = ['*'];

    public function add(Request $request)
    {
        $openid = $request->param('openid');
        $token = $request->header('token');
        $ismember = db('user')->where('open_id', '=', $openid)->find();
        if ($ismember) {
            if ($ismember['group_id'] == 2 ) {
                return json(['code' => 400, 'msg' => '只有绑定过手机号的会员才可以发表评论1']);
            } else {
                $workerid = $request->param('workerid');
                $storeid=$request->param('storeid');
                $content = $request->param('content');
                $imageData = $request->param('imageData');

                if (!empty($imageData)){//图片上传了再处理
                    $imgarr=explode('|',$imageData);
                    $src=[];
                    if($imgarr>1){
                        foreach ($imgarr as $k=>$v){
                            $src[$k]=Comment::singleImagesHandle($imgarr[$k],'/comments');
                        }
                    }else{
                        $src[0]=Comment::singleImagesHandle($imgarr[0],'/comments');
                    }
                }else{
                    $src="";
                }
                if(!empty($storeid)){
                    $data = [
                        'uid' => $ismember['id'],
                        'content' => $content,
                        'storeid' => $storeid,
                        'imageData' => json_encode($src),
                        'addtime' => time()
                    ];
                    $rule = [
                        'content' => ['require'],
                        'storeid' => ['require'],
                        'uid' => ['require']
                    ];
                    $validate = new \think\Validate($rule);
                    if (!$validate->check($data)) {
                        return json(['code' => 400, 'msg' => $validate->getError()]);
                    } else {
                        $words = db('bugword')->select();
                        foreach ($words as $item) {
                            $bug = $item['word'];
                            $data['content'] = preg_replace("/$bug/", '*', $data['content']);
                        }
                        $ispublish = db('comment')->data($data)->insert();
                        if ($ispublish) {
                            db('store')->where('storeid','=',$storeid)->setInc('comment');
                            return json(['code' => 200, 'msg' => '评论成功']);
                        } else {
                            return json(['code' => 400, 'msg' => '评论失败']);
                        }
                    }
                }
                if(!empty($workerid)){
                    $data = [
                        'uid' => $ismember['id'],
                        'content' => $content,
                        'workerid' => $workerid,
                        'imageData' => json_encode($src),
                        'addtime' => time()
                    ];

                    $rule = [
                        'content' => ['require'],
                        'workerid' => ['require'],
                        'uid' => ['require']
                    ];

                    $validate = new \think\Validate($rule);
                    if (!$validate->check($data)) {
                        return json(['code' => 400, 'msg' => $validate->getError()]);
                    } else {
                        $words = db('bugword')->select();
                        foreach ($words as $item) {
                            $bug = $item['word'];
                            $data['content'] = preg_replace("/$bug/", '*', $data['content']);
                        }
                        $ispublish = db('comment')->data($data)->insert();
                        if ($ispublish) {
                            db('worker')->where('workerid','=',$workerid)->setInc('coment');
                            return json(['code' => 200, 'msg' => '评论成功']);
                        } else {
                            return json(['code' => 400, 'msg' => '评论失败']);
                        }
                    }
                }
            }
        } else {
            return json(['code' => 400, 'msg' => '请您先]登录']);
        }
    }


    /**
     * 单图上传
     */
    public static function singleImagesHandle($images,$filename)
    {
        $picBase64Data = preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($images), $result) ? trim($images) : '';
        $dirName = '';
        if(!empty($picBase64Data))
        {
            $picBase64NewData = str_replace($result[1], '', $picBase64Data);
            $type = $result[2];

            $dir='uploads'.$filename;
            $name = md5(time() . rand(10,99)). '.' . $type;

            if(is_dir($dir))
            {
                if((file_exists($dir . '/' .$name) || file_put_contents($dir . '/' .$name,base64_decode($picBase64NewData))))
                {
                    $dirName = '/' . $dir . '/' .$name;
                }
            }
        }
        return $dirName;
    }

    /**
     * @param $data
     * @param $filename
     * @return array
     * 多图片上传
     */
    public static function multiImagesHandle($data,$filename)
    {
        $covers = array();
        if(!empty($data))
        {
            if(!is_array($data))
            {
                $coverImgs = json_decode($data);
            }else{
                $coverImgs = $data;
            }

            foreach ($coverImgs as $imgKey => $imgVal)
            {
                if($imgKey >= 8){break;}

                if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $imgVal, $result))
                {
                    $picBase64NewData = str_replace($result[1], '', $imgVal);
                    $type = $result[2];
                    $name = md5(time() . rand(10,99)) . '.' . $type;
                    $dir='/uploads'.$filename;

                    if(is_dir($dir))
                    {
                        if((file_exists($dir . '/' . $name) || file_put_contents($dir . '/' . $name,base64_decode($picBase64NewData))))
                        {
                            $covers[] = '/' . $dir . '/' . $name;
                        }
                    }
                }else{
                    $covers[] = $imgVal;
                }
            }
        }

        return $covers;
    }
}